<?php
require_once('sn_functions.php');

$date1 = isset($_GET["date1"]) ? $_GET["date1"] : "";
$date2 = isset($_GET["date2"]) ? $_GET["date2"] : "";
$sensor_id = isset($_GET["sensors"]) ? $_GET["sensors"] : ""; 
$data_dir = get_data_folder($sensor_id);

if ($date1 > $date2){
	echo "Select correct data intervals!";
}else{
	$START_DATE = get_date_format($date1);
	$END_DATE = get_date_format($date2);
//	echo 'data_dir:'.$data_dir;
	if (is_dir($data_dir)){
		$dir = opendir($data_dir);
		$elements = sort_dir($dir);		
		$i=0;
		$first = true;
		$is_data = false; 
		while ($i < sizeof($elements)){
			$element = $elements[$i];
			$name = get_name($element);
			$extension = get_extension($element);
//			echo "element: $element name:$name extension:$extension";
			if($extension == "txt"){
//			echo "TXT:element: $element name:$name extension:$extension";
				if(($name >= $START_DATE) && ($name <= $END_DATE)){
					//Only to do with the first file
					if ($first){
						$first = false;
						$filefullpath =  $data_dir . "/" .  $element;
						$headers = read_headers($filefullpath);
						for($j=0; $j<sizeof($headers); $j++){
							$line = $headers[$j];
							show_data($line);
						}
					}
					$file = fopen($filefullpath, "r");
					$is_data = true;
					$k=0;
					while(!feof($file)){
						//Nothing to do with the first two lines
						if (($k != 0) && ($k != 1)){
							$line = fgets($file);
							show_data($line);
						}
						else{
							$line = fgets($file);
						}
						$k++;
					}
					fclose($file);
				}
			}
			$i++;
		}
		if (!$is_data){
			echo "Data is not avaliable";
		}
		closedir($dir);
	}
}
?>